$.fn.popover_close=function(){
	$(this).parents('.popover-cnt').remove();
}
$.popover=function(args){
	$.ajax({
		url:args.url,data:args.data,error:function(data){
			if(args.error){
				args.error(data);
			}else{
				data=$.parseJSON(data.responseText);
				$.popover_alert({
					message:data.error,link:data.link,offset_parent:args.offset_parent});
			}
		},
		success:function(data){
			var popover_parent=$('body');
			if(args.offset_parent&&args.offset_parent.offset()){
				offset_parent=args.offset_parent;
				popover_left=offset_parent.offset().left;
				popover_top=offset_parent.offset().top;
			}else{
				offset_parent=$(window);
				popover_left=$(window).scrollLeft();
				popover_top=$(window).scrollTop();
			}
			var offset_parent_w=offset_parent.width();
			var offset_parent_h=offset_parent.height();
			if(!args.attach){
				$('.popover-cnt').remove();
			}
			var popover_cnt=$("<div/>",{"class":"popover-cnt"}).appendTo(popover_parent);
			popover_cnt.html(data);
			$('.popover-cnt').delegate('.po-close','click',function(){
				$(this).popover_close();
				return false;
			});
			if(args.horizon=='left'){
				
			}else if(args.horizon=='right'){
					popover_left+=(offset_parent_w-popover_cnt.width());
			}else{
				popover_left+=(offset_parent_w-popover_cnt.width())/2;
			}
			if(args.vertical=='top'){
			
			}else if(args.vertical=='bottom'){
				popover_top+=(offset_parent_h-popover_cnt.height());
			}else{
				popover_top+=(offset_parent_h-popover_cnt.height())/2;
			}
			popover_cnt.offset({
				left:popover_left,top:popover_top
			});
			if(args.success){
				args.success(data);
			}
		}
	});
}
$.popover_confirm=function(args){
	args=$.extend({
		attach:true,
		url:'/popover/confirm',
		success:function(){
			$('.popover-cnt').delegate('.po-confirm','click',function(){
				if(args.confirm){
					args.confirm();
				}
				$(this).popover_close();
				return false;
			});
		},
		data:{
			message:args.message
		}
	},args);
	$.popover(args);
}
$.popover_alert=function(args){
	args=$.extend({
		attach:true,url:'/popover/alert',data:{
			message:args.message,link:args.link
		}
	},args);
	$.popover(args);
}